home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 8153 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.1 KB  |  74 lines

  1. Path: macqbl.com.au!usenet
  2. From: steven@macquarie.com.au (Steven James Brown)
  3. Newsgroups: comp.lang.c++
  4. Subject: A curly one for gurus: possible to create a value array of derived objects?
  5. Date: 15 Feb 1996 05:53:06 GMT
  6. Organization: Macquarie Bank
  7. Distribution: world
  8. Message-ID: <4fuho2$d3s@mblisd.macqbl.com.au>
  9. Reply-To: steven@macquarie.com.au
  10. NNTP-Posting-Host: qad10.macqbl.com.au
  11.  
  12.  
  13. Ok This is a real curly question:
  14.  
  15. Is it possible to create (and manage) a "value" array of objects from 
  16. derived classes?
  17.  
  18. E.g:
  19.  
  20. struct A { virtual char* name() { return "A"; } };
  21. struct B : public A { int    data1; virtual char* name() { return "B"; }  };
  22. struct C : public A { double data2; virtual char* name() { return "C"; }  };
  23.  
  24. To be able to provide access to an array of B's and C's without occuring
  25. the overhead of pointer indirection, I am hoping it is somehow possible to
  26. have something like:
  27.  
  28. #include <stdio.h>
  29. main()
  30. {
  31.     A* a = new A[10];
  32.     B b;
  33.     C c;
  34.  
  35.     a[0] = b;
  36.     a[1] = c;
  37.  
  38.     printf("%s\n", a[0].name());
  39.     printf("%s\n", a[1].name());
  40. }
  41.  
  42.  
  43. The output from this (as you may have already guessed) is 
  44. A
  45. A
  46.  
  47. and not 
  48. B
  49. C
  50.  
  51. The problem here is I guess "data slicing" and the use of the default operator=. 
  52. Is it possible to somehow get over this
  53. by faking a union? I can't use unions in practice because my derived classes
  54. have (default) constructors.
  55.  
  56. The idea for this came from the "Composite" pattern in the Design Patterns
  57. book by Gamma/Helm/Johnson/Vlissides. The "A" class above being the "Composite"
  58. object, and the "B" and "C" being the "Component" objects. 
  59.  
  60. Thanks for any solutions/suggestions you can provide.
  61. Steve
  62. ---
  63.  
  64. ////////////////////////////////////////////////////////////////////////////
  65. // Steven James Brown                       Disclaimer: Any comments or   //
  66. // Qantitative Applications                 views made are my own and are //
  67. // Macquarie Bank Limited                   unrelated to those of my      //
  68. // steven@macquarie.com.au                  employer.                     //
  69. //                                                                        //
  70. ////////////////////////////////////////////////////////////////////////////
  71.  
  72.  
  73.  
  74.